package com.example.pages;

import static org.openqa.selenium.support.ui.ExpectedConditions.alertIsPresent;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.testng.collections.Lists;

import com.example.tests.User;

public class ManagementPage extends InternalPage {
	
	@FindBy(id = "username")
	public WebElement userNameField;
	
	@FindBy(name = "email")
	public WebElement emailField;
	
	@FindBy(id = "password")
	public WebElement passwordField;
	
	@FindBy(id = "password2")
	public WebElement password2Field;
	
	@FindBy(name = "submit")
	public WebElement saveButton;
	
	@FindBy(css = "table img[title=\"Edit\"]")
	public List<WebElement> editButtons;
	
	@FindBy(xpath = "//div[2]/table/tbody/tr")
	public List<WebElement> userRows;

	public int getUserCount() {
		return editButtons.size();
	}
	
	public boolean isOnThisPage() {
		return editButtons.get(0).isDisplayed();
	}

	public ManagementPage createUser(User user) {
		userNameField.clear();
		userNameField.sendKeys(user.name);
		emailField.clear();
		emailField.sendKeys(user.email);
		passwordField.clear();
		passwordField.sendKeys(user.password);
		password2Field.clear();
		password2Field.sendKeys(user.password);
		saveButton.click();
		return MyPageFactory.getPage(driver, ManagementPage.class);
	}
	
	public ManagementPage deleteUser(User user) {
		for (WebElement row : userRows) {
			if (user.equals(convertRowToUser(row))) {
				row.findElement(By.xpath("./td[6]/a")).click();
				wait_().until(alertIsPresent()).accept();
				break;
			}
		}
		return MyPageFactory.getPage(driver, ManagementPage.class);	
	}
	
	public ManagementPage deleteAnyUser() {
		for (WebElement row : userRows) {
			User user = convertRowToUser(row);
			if (!user.role.equals("Admin")) {
				row.findElement(By.xpath("./td[6]/a")).click();
				wait_().until(alertIsPresent()).accept();
				break;
			}
		}
		return MyPageFactory.getPage(driver, ManagementPage.class);	
	}

	public List<User> getUsers() {
		List<User> users = Lists.newArrayList();
		for (WebElement row : userRows) {
			users.add(convertRowToUser(row));
		}
		return users;
	}

	private User convertRowToUser(WebElement row) {
		List<WebElement> cells = row.findElements(By.tagName("td"));
		return new User()
		.withName(cells.get(1).getText())
		.withEmail(cells.get(2).getText())
		.withRole(cells.get(3).getText());
	}
}
